<?php
/**
 * RedXenon Framework
 * 
 * LICENSE
 * 
 * This source file is subject to the New BSD license that is bundled
 * with this package in the file LICENSE.txt
 * A copy of this license can be found in the world-wide-web at this URL:
 * http://www.redxenon.com/license/new-bsd-license.txt * 
 */

/* Abstract class */
require_once("RXAbstractFormElement.php");

/**
 * RedXenon Form (RXSelect.php)
 * Defines methods to create Select elements
 * 
 * The Data Array structure must be:
 * array(array["value" => X, "label" => Y])
 * 
 * @category RedXenon
 * @package RedXenon_Form
 * @copyright Copyright (c) 2011 Red Xenon (http://www.redxenon.com)
 * @version $Id: RXSelect.php 1.0 2011-05-02 $ 
 */
class RXSelect extends RXAbstractFormElement{
	
	/**
	 * Selected value from the select field
	 * @var String
	 */
	private $value;
	
	/**
	 * Set of available selected options
	 * @var Array
	 */
	private $data;
	
	/**
	 * Creates a new instance of the class
	 * @param String $name
	 * @param Array $data
	 * @param String $value
	 */
	public function __construct($name = NULL, $data = NULL, $value = NULL){
		$this->data = $data;
		if(!is_array($this->data))
			$this->data = array();
		$this->value = $value;
		parent::__construct($name);
	}
	
	/**
	 * Sets a new set of data
	 * @param Array $data
	 */
	public function setData($data){
		$this->data = $data;
	}
	
	/**
	 * Sets a new selected value
	 * @param String $value
	 */
	public function setValue($value){
		$this->value = $value;
	}
	
	/**
	 * Adds a new option to the select
	 * @param String $value
	 * @param String $label
	 */
	public function addData($value, $label){
		array_push($this->data, array("value" => $value, "label" => $label));
	}
	
	/**
	 * Returns a HTML code that represents a 
	 * Select Field
	 * @return String
	 */
	public function getOutput(){
		$ret = "<select";
		
		if(isset($this->name))
			$ret .= ' name="'.$this->name.'"';
		if(isset($this->id))
			$ret .= ' id="'.$this->id.'"';
				
		$ret .= ">\n";
		
		foreach($this->data as $data){
			if($data["value"] == $this->value){
				$ret .= '\t<option value="'.$data["value"].'" selected>'.$data["label"].'</option>\n';
			}else{
				$ret .= '\t<option value="'.$data["value"].'">'.$data["label"].'</option>\n';
			}
		}
				
		$ret .= "</select>";
		
		return $ret;
	}
}